package xxy.com.yangproject.ui.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.widget.ProgressBar;

import xxy.com.yangproject.R;


/**
 * 作者：xxy on 2018/3/29 14:31
 */
public class ProgressUpdate extends ProgressBar {

    private static final int DEFAULT_TEXT_SIZE = 10;
    private static final int DEFAULT_TEXT_COLOR = 0XFFFC00D1;
    private static final int DEFAULT_COLOR_UNREACHED_COLOR = 0xFFd3d6da;
    private static final int DEFAULT_HEIGHT_REACHED_PROGRESS_BAR = 2;
    private static final int DEFAULT_HEIGHT_UNREACHED_PROGRESS_BAR = 2;
    private static final int DEFAULT_TEXT_RECT_COLOR = 0xFFFFFFFF;
    private  Paint mPaintBubble;
    protected Paint mPaint = new Paint();
    // 字体颜色
    protected int mTextColor = DEFAULT_TEXT_COLOR;
    // 字体大小
    protected int mTextSize = sp2px(DEFAULT_TEXT_SIZE);
    // 覆盖进度高度
    protected int mReachedProgressBarHeight = dp2px(DEFAULT_HEIGHT_REACHED_PROGRESS_BAR);
    // 覆盖进度颜色
    protected int mReachedBarColor = DEFAULT_TEXT_COLOR;
    // 未覆盖进度高度
    protected int mUnReachedProgressBarHeight = dp2px(DEFAULT_HEIGHT_UNREACHED_PROGRESS_BAR);
    // 未覆盖进度颜色
    protected int mUnReachedBarColor = DEFAULT_COLOR_UNREACHED_COLOR;
    // 圆的颜色
    protected int mRectColor = DEFAULT_TEXT_RECT_COLOR;
    protected int mCircleColor = getResources().getColor(R.color.orange);
    protected int mRealWidth;
    protected boolean mIfDrawText = true;
    protected boolean mIfDrawCircle = true;
    protected static final int VISIBLE = 0;
    private Paint mPaintProgressStr;
    private String mProgressStr;
    private String text;
    private float mProgressStrMargin = 15;//气泡的边距
    private Path mPathBubble = new Path(); //气泡的路径
    private float endX;
    private float progressPosX;
    private float mBubbleTriangleHeight = 10;//气泡底部小三角高度
    private float mBubbleRectRound = 5;//气泡的圆角
    private Paint.FontMetricsInt mFontMetricsInt;

    public ProgressUpdate(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ProgressUpdate(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        obtainStyledAttributes(attrs);
        initPaint();
    }

    private void initPaint() {
        //文字画笔
        mPaint.setTextSize(mTextSize);
        mPaint.setColor(mTextColor);
        mPaint.setAntiAlias(true);
        mFontMetricsInt = mPaint.getFontMetricsInt();

        //气泡画笔
        mPaintBubble = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaintBubble.setStrokeCap(Paint.Cap.ROUND);//设置线头为圆角
        mPaintBubble.setStyle(Paint.Style.FILL);
        mPaintBubble.setStrokeJoin(Paint.Join.ROUND);//设置拐角为圆角
    }

    private void obtainStyledAttributes(AttributeSet attrs) {
        // 获取自定义属性
        final TypedArray attributes = getContext().obtainStyledAttributes(attrs, R.styleable.ProgressUpdate);
        mTextColor = attributes.getColor(R.styleable.ProgressUpdate_progress_text_color, DEFAULT_TEXT_COLOR);
        mTextSize = (int) attributes.getDimension(R.styleable.ProgressUpdate_progress_text_size, mTextSize);
        mRectColor = attributes.getColor(R.styleable.ProgressUpdate_progress_text_rec_color, DEFAULT_TEXT_RECT_COLOR);
        mReachedBarColor = attributes.getColor(R.styleable.ProgressUpdate_progress_reached_color, mTextColor);
        mUnReachedBarColor = attributes.getColor(R.styleable.ProgressUpdate_progress_unreached_color, DEFAULT_COLOR_UNREACHED_COLOR);
        mReachedProgressBarHeight = (int) attributes.getDimension(R.styleable.ProgressUpdate_progress_reached_bar_height, mReachedProgressBarHeight);
        mUnReachedProgressBarHeight = (int) attributes.getDimension(R.styleable.ProgressUpdate_progress_unreached_bar_height, mUnReachedProgressBarHeight);
        int textVisible = attributes.getInt(R.styleable.ProgressUpdate_progress_text_visibility, VISIBLE);
        if (textVisible != VISIBLE) {
            mIfDrawText = false;
        }
        attributes.recycle();
        int left = (int) (mReachedProgressBarHeight * 0.8 + dp2px(15)), right = (int) (mReachedProgressBarHeight * 0.9 + dp2px(10));
        int top = (int) (mReachedProgressBarHeight * 0.3 + dp2px(1)), bottom = (int) (mReachedProgressBarHeight * 0.3 + dp2px(1));
        setPadding(left, top, right, bottom);
    }

    @Override
    protected synchronized void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int width = MeasureSpec.getSize(widthMeasureSpec);
        int height = measureHeight(heightMeasureSpec);
        setMeasuredDimension(width, height);
        mRealWidth = getMeasuredWidth() - getPaddingRight() * 2 - getPaddingLeft() ;
    }

    private int measureHeight(int measureSpec) {
        int result;
        int specMode = MeasureSpec.getMode(measureSpec);
        int specSize = MeasureSpec.getSize(measureSpec);
        if (specMode == MeasureSpec.EXACTLY) {
            result = specSize;
        } else {
            float textHeight = (mPaint.descent() - mPaint.ascent());
            result = (int) (getPaddingTop() + getPaddingBottom() + Math.max(
                    Math.max(mReachedProgressBarHeight, mUnReachedProgressBarHeight), Math.abs(textHeight)) * 4); //Math.abs(textHeight)) * 4 是实验得来的高度结果
            if (specMode == MeasureSpec.AT_MOST) {
                result = Math.min(result, specSize);
            }
        }
        return result;
    }

    @Override
    protected synchronized void onDraw(Canvas canvas) {
        canvas.save();
        canvas.translate(getPaddingLeft(), getHeight() / 2);
        boolean noNeedBg = false;
        float radio = getProgress() * 1.0f / getMax();
        progressPosX = (int) (mRealWidth * radio);
        text = getProgress() + "%";
        float textWidth = mPaint.measureText(text);
        float textHeight = (mPaint.descent() + mPaint.ascent()) / 2;
//        float radius = (mReachedProgressBarHeight + getPaddingBottom() + getPaddingTop()) / 2;
        float radius = Math.max(textWidth, textHeight) / 2;
        // 覆盖的进度
        endX = progressPosX;
        if (endX > -1) {
            mPaint.setColor(mReachedBarColor);
            RectF rectF = new RectF(0, 0 - getPaddingTop() - getPaddingBottom(),
                    endX, mReachedProgressBarHeight - getPaddingBottom());
            canvas.drawRoundRect(rectF, 25, 25, mPaint);
        }
        // 未覆盖的进度
        if (!noNeedBg) {
            float start = progressPosX;
            mPaint.setColor(mUnReachedBarColor);
            RectF rectF = new RectF(start, 0 - getPaddingTop() - getPaddingBottom(),
                    mRealWidth /*+ getPaddingRight() - radius*/, mReachedProgressBarHeight - getPaddingBottom());
            canvas.drawRoundRect(rectF, 25, 25, mPaint);
        }
        //氣泡
        paintBubble(canvas);
        // 文本，位置在覆盖的进度条终点处
//        if (mIfDrawText) {
//            mPaint.setColor(mTextColor);
//            canvas.drawText(text, progressPosX, -textHeight, mPaint);
//        }
        canvas.restore();
    }

    private void paintBubble(Canvas canvas) {
        Rect rect = new Rect();
        mPaint.getTextBounds(text,0,text.length(),rect);//返回包围整个字符串的最小的一个Rect区域，以此计算出文字的高度和宽度
        int width = (int) (rect.width()+mProgressStrMargin);//计算字符串宽度(加上设置的边距)
        int height = (int) (rect.height()+mProgressStrMargin);//计算字符串高度(加上设置的边距)
        mPathBubble.reset();
        float progressHeight = mReachedProgressBarHeight - getPaddingBottom() *2;
        mPathBubble.moveTo(progressPosX,progressHeight - mReachedProgressBarHeight);  //畫筆移動
        mPathBubble.lineTo(progressPosX+mBubbleTriangleHeight,progressHeight-mBubbleTriangleHeight-mReachedProgressBarHeight);//假设底部小三角为等腰直角三角形，那么三角形的高度就等于底边长度的1/2
        mPathBubble.lineTo(progressPosX-mBubbleTriangleHeight,progressHeight-mBubbleTriangleHeight-mReachedProgressBarHeight);
        mPathBubble.close();//使路径闭合从而形成三角形
        //这里是计算文字所在矩形的位置及大小
        //left:因为设置的气泡底部三角形为等腰直角三角形，所以矩形的左边位置为，
        //      进度所在的横坐标 - 底部三角形高度 - 矩形圆角的半径(不减去圆角半径的话显得不够圆润)，
        //      (width / 2f)代替了这个(getProgress() * 0.01f *width)为了不断改变气泡底部的三角形与气泡顶部矩形的相对位置的方案
        //      否则在进度条开始或结束位置可能为显示不全
        //top:进度所在的高度 - 底部三角形高度 - 进度条高度 - 矩形高度
        //right:矩形右边位置的计算原理与左边相同，同样((1-mProgress)*width)也是为了不断改变气泡底部的三角形与气泡顶部矩形的相对位置（与left相对应）
        //bottom:这个就简单了，与top相比小了一个矩形的高度
        RectF rectF = new RectF(progressPosX-mBubbleTriangleHeight-mBubbleRectRound/2-(width / 2f),progressHeight-mBubbleTriangleHeight-mReachedProgressBarHeight-height,progressPosX+mBubbleTriangleHeight+mBubbleRectRound/2+(width / 2f),progressHeight-mBubbleTriangleHeight-mReachedProgressBarHeight);
        mPathBubble.addRoundRect(rectF,mBubbleRectRound,mBubbleRectRound, Path.Direction.CW);//添加矩形路径
        canvas.drawPath(mPathBubble,mPaintBubble);//绘制气泡
        int i = (mFontMetricsInt.bottom - mFontMetricsInt.ascent) / 2 - mFontMetricsInt.bottom;//让文字垂直居中
        canvas.drawText(text,rectF.centerX() - width / 2f,rectF.centerY()+i,mPaint);//绘制文字（将文字绘制在气泡矩形的中心点位置）, (width / 2f)代替了(getProgress() * 0.01f *width)方案获取字符串变化宽度
    }

    /**
     * dp 2 px
     */
    protected int dp2px(int dpVal) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpVal, getResources().getDisplayMetrics());
    }

    /**
     * sp 2 px
     */
    protected int sp2px(int spVal) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, spVal, getResources().getDisplayMetrics());
    }
}
